var express = require('express');
var router = express.Router();
var {user_model , xueke_model,banji_model,good_model,cart_model, like_model,shou_model,payorder_model,comment_model} = require('../db/model')
var {findOneFromTable, updateOneFromTable, updateTableData,FindAllFromTable, insertOneFromTable,removeTableData , removeOneFromTable,findOneTableData} = require('../utils')
var axios = require('axios');
const { createToken, checkToken } = require('../utils/token');

const multer = require('multer');
const { json } = require('express');
router.all("/test",(req,res)=>{
    res.json({
        code:200,
        msg:"测试API接口是否成功",
        result:null 
    })
})
 

// 注册
router.post("/register",async (req,res)=>{
    var body = req.body;
    let result = await user_model.findOne({
        $or:[  // 或
            {
                username:body.username,
            },
            {
                phone:body.phone
            }
        ]
    }).catch(err=>{
        res.json({
            code:500,
            msg:"服务器异常",
            err
        })
    })
    if(result){
        res.json({
            code:401,
            msg:"当前用户已经存在,请重新注册",
            result,
        })
    }else{
        // 插入数据 
        body.time = new Date();
        let data = await user_model.insertMany(body)
        res.json({
            code:200,
            msg:"注册成功",
            result:data,
        })
    }
})

// 用户名登录
router.post("/logindemo",async (req,res)=>{
    var body = req.body;
    let result = await user_model.findOne(body).catch(err=>{
        res.json({
            code:500,
            msg:"服务器异常",
            err
        })
    })
    if(result){
        res.json({
            code:200,
            msg:"登录成功",
            result
        })
    }else{
        res.json({
            code:401,
            msg:"登录失败,用户名和密码不匹配",
            result:null 
        })
    }
})

// 
router.all("/login",async (req,res)=>{
    var body = req.body;
    findOneFromTable({
        model:user_model,
        res,
        query:body,
        callback:result=>{  // 执行下一步操作 
            if(result){
                // token
                const token = createToken({
                    username:result.username,
                    phone:result.phone,
                    password:result.password
                }) 
                res.json({
                    code:200,
                    msg:"登录成功",
                    result,
                    token
                })
            }else{
                res.json({
                    code:401,
                    msg:"登录失败,用户名和密码不匹配",
                    result:null 
                })
            }
        }
    })
})


// 发送验证码
router.post("/sentcaptcha",(req,res)=>{
  var body = req.body;
  findOneFromTable({
      model:user_model,
      query:{phone:body.phone},  // 先判断手机号是否注册 
      res,
      callback:(result)=>{
          if(result){
              // 发送验证码
              axios.get("http://47.104.209.44:3333/captcha/sent",{
                  params:body,
              })
              .then(data=>{
                  console.log(data.data)
                  if(data.data.code==200){
                      res.json({
                          code:data.data.code,
                          msg:"验证码发送成功",
                          data:data.data 
                      })
                  }else{
                      res.json({
                          code:data.data.code,
                          msg:"验证码发送失败",
                          data:data.data 
                      })
                  }
                  
              })
              .catch(err=>{
                  res.json({
                      code:500,
                      msg:"服务器异常",
                      err
                  })
              })
          }else{
              res.json({
                  code:401,
                  msg:"手机号未注册,请先注册",
                  result:null 
              })
          }
      }
  })
})

// 验证验证码
router.post("/verifycaptcha",(req,res)=>{
  var body = req.body; // phone captcha 
  findOneFromTable({
      model:user_model,
      query:{phone:body.phone},  // 先判断手机号是否注册 
      res,
      callback:(result)=>{
          if(result){
              // 发送验证码
              axios.get("http://47.104.209.44:3333/captcha/verify",{
                  params:body,
              })
              .then(data=>{
                  if(data.data.code==200){
                      // token 
                      const token = createToken({
                          username:result.username,
                          phone:result.phone,
                          password:result.password
                      })
                      res.json({
                          code:data.data.code,
                          msg:"验证码校验成功",
                          data:data.data,
                          token
                      })
                  }else{
                      res.json({
                          code:data.data.code,
                          msg:"验证码校验失败",
                          data:data.data 
                      })
                  }
                  
              })
              .catch(err=>{
                  res.json({
                      code:500,
                      msg:"服务器异常",
                      err
                  })
              })
          }else{
              res.json({
                  code:401,
                  msg:"手机号未注册,请先注册",
                  result:null 
              })
          }
      }
  })
})


// 获取用户信息
router.all("/getuserinfo",(req,res)=>{
 
    checkToken(req,res,({username})=>{
        findOneFromTable({
            model:user_model,
            query:{username},
            res,
            msg:"获取个人信息成功"
        })
    })
})

// 修改密码
router.all("/changepass",(req,res)=>{
    var body=req.body;
    checkToken(req,res,({username,password})=>{
        if(body.oldpass==password){
            updateOneFromTable({
                model:user_model,
                res,
                query:{
                    username
                },
                data:{
                    password:body.newpass
                },
                msg:"修改成功"
            })
        }else{
            res.json({
                code:401,
                msg:"旧密码不正确不能修改",
                result:null
            })
        }
    })
})

// 上传文件
const storage = multer.diskStorage({  // 硬盘存储 
    destination: function (req, file, cb) {
      cb(null, './public/images')   // 文件保存的路径 
    },
    filename: function (req, file, cb) {
      const uniqueSuffix = "WH2201__"+Date.now() + '-' + Math.round(Math.random() * 1E9)   // 文件名、 
      cb(null, file.fieldname + '-' + uniqueSuffix + file.originalname)   //时间戳（为了避免文件名冲突）
    }
})

const upload = multer ({storage:storage}).any()

// 上传文件（头像）

router.all("/uploadfiles",upload,(req,res)=>{
    var path = req.files[0].path; // 文件路径 ： 相对于服务器路径
    checkToken(req,res,({username,password})=>{
        res.json({
            code:200,
            msg:"上传成功",
            path,
            result:path
        })
    })
})



// 修改用户信息
router.all("/changeuserinfo",(req,res)=>{
    var body =req.body;
    checkToken(req,res,({username,password})=>{
        updateOneFromTable({
            model:user_model,
            res,
            query:{
                username
            },
            data:body,
            msg:"修改成功"
        })
    })
})


// 找回密码
router.all("/findpass",(req,res)=>{
    var body = req.body;
    findOneFromTable({
        model:user_model,
        query:{phone:body.phone},  // 先判断手机号是否注册 
        res,
        callback:(result)=>{
            if(result){
                // 校验验证码
                axios.get("http://47.104.209.44:3333/captcha/verify",{
                    params:{
                        phone:body.phone,
                        captcha:body.captcha 
                    },
                })
                .then(data=>{
                    if(data.data.code==200){
                        // 修改密码 
                        console.log(body)
                        updateOneFromTable({
                            model:user_model,
                            res,
                            query:{
                                phone:body.phone
                            },
                            data:{
                                password:body.password
                            },
                            msg:"密码找回成功"
                        })
                    }else{
                        res.json({
                            code:data.data.code,
                            msg:"验证码校验失败",
                            data:data.data 
                        })
                    } 
                })
            }else{
                res.json({
                    code:401,
                    msg:"手机号未注册,请先注册",
                    result:null 
                })
            }
        }
    })
})



// 添加学科 
router.all("/xuekeadd",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        findOneFromTable({
            model:xueke_model,
            res,
            query:{
                value:body.value 
            },
            callback:result=>{
                console.log(result)
                if(result){
                    res.json({
                        code:401,
                        msg:"当前学科已经存在,请重新添加",
                        result
                    })
                }else{
                    // 添加学科 
                    // id 
                    FindAllFromTable({
                        model:xueke_model,
                        sort:{
                            id:-1  // 1 升序 -1 降序
                        },
                        limit:1,
                        res,
                        callback:(value)=>{
                            // 
                            console.log(value)
                            body.id = value[0] ? value[0].id + 1 : 1; 
                            console.log(body)
                            insertOneFromTable({
                                model:xueke_model,
                                res,
                                data:body,
                                msg:'学科添加成功'
                            })
                        }
                    })
                }
            }
        })
    })
})


// 查询学科
router.all("/xuekelist",(req,res)=>{
    var body = req.body;
    var obj={}
    var keyword = body.keyword;
    if(keyword){
        obj={
            $or:[
                {
                    // 以名字
                    name:new RegExp(keyword)
                },{
                    // 或者编码搜索
                    value:new RegExp(keyword)
                }
            ]
        }
    }
    checkToken(req,res,({username})=>{
        FindAllFromTable({
            model:xueke_model,
            query:obj,
            res,
            msg:"查询学科成功"
        })
    })
})

// 删除学科
router.all("/xuekedel",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        removeOneFromTable({
            model:xueke_model,
            query:{
                _id:body._id 
            },
            res,
            msg:"删除学科成功"
        })
    })
})

// 修改学科
router.all("/xuekeupdata",(req,res)=>{
    var body = req.body;
    // console.log(body._id);
    checkToken(req,res,({username})=>{
        updateTableData({
            model:xueke_model,
            query:{
                _id:body._id 
            },
            res,
            data:body,
            msg:"学科修改成功"
        })
    })
})

// 添加班级
router.all("/banjiadd",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        findOneFromTable({
            model:banji_model,
            res,
            query:{
                value:body.value 
            },
            callback:result=>{
                console.log(result)
                if(result){
                    res.json({
                        code:401,
                        msg:"当前班级已经存在,请重新添加",
                        result
                    })
                }else{
                    // 添加学科 
                    // id 
                    FindAllFromTable({
                        model:banji_model,
                        sort:{
                            id:-1  // 1 升序 -1 降序
                        },
                        limit:1,
                        res,
                        callback:(value)=>{
                            // 
                            console.log(value)
                            body.id = value[0] ? value[0].id + 1 : 1; 
                            console.log(body)
                            insertOneFromTable({
                                model:banji_model,
                                res,
                                data:body,
                                msg:'添加成功'
                            })
                        }
                    })
                }
            }
        })
    })
})

// 查询班级
router.post("/banjilist",(req,res)=>{
    var body = req.body;
    var obj = {}
    var keyword = body.keyword;
    var xueke = body.xueke;
    if(keyword && xueke){
        obj = {
            banji_xueke:xueke,
            banji_text:new RegExp(keyword)
        }
    }
    if(keyword && !xueke ){
        obj = {
            banji_text:new RegExp(keyword)
        }
    }
    if(xueke && !keyword){
        obj = {
            banji_xueke:xueke
        }
    }
    checkToken(req,res,({username})=>{
        FindAllFromTable({
            model:banji_model,
            query:obj,
            sort:{_id:-1},
            res,
            msg:"查询班级成功"
        })
    })
})
// 删除班级
router.post("/banjidel",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        removeOneFromTable({
            model:banji_model,
            query:{
                _id:body._id 
            },
            res,
            msg:"删除成功"
        })
    })
})
// 修改班级
router.post("/banjiset",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        findOneFromTable({
            model:xueke_model,
            res,
            query:{
                value:body.banji_xueke 
            },
            callback:result=>{
                console.log(result)
                body.banji_no =   body.banji_no < 10 ? '0'+body.banji_no : body.banji_no;
                body.banji_year =  body.banji_year.toString().split("").slice(2,4).join("")
                body.banji_value =  body.banji_xueke+body.banji_year +body.banji_no;
                body.banji_text =   result.name+"WH"+body.banji_year +body.banji_no;
                console.log(body)
                findOneFromTable({
                    model:banji_model,
                    query:{
                        banji_value:body.banji_value
                    },
                    res,
                    callback:data=>{
                        if(data){
                            res.json({
                                code:401,
                                msg:'班级已经存在',
                                result:data 
                            })
                        }else{
                            updateOneFromTable({
                                model:banji_model,
                                query:{
                                    _id:body._id,
                                },
                                data:body,
                                res,
                                msg:'班级修改成功'
                            })
                        }
                    }
                })
            }
        })
    })
})

// 添加公告
router.post("/annoadd",(req,res)=>{
    var body = req.body;
    body.time = new Date()
    checkToken(req,res,({username})=>{
        insertOneFromTable({
            model:anno_model,
            data:body,
            msg:"添加公告成功",
            res, 
        })
    })
})

// 查询公告
router.post("/annolist",(req,res)=>{
    var body = req.body;    
    var obj = {}
    checkToken(req,res,({username})=>{
        FindAllFromTable({
            model:anno_model,
            query:obj,
            sort:{_id:-1},
            res,
            msg:"查询成功"
        })
    })
})



// 留言板增删改查 
router.all("/addcomment",(req,res)=>{
    var body = req.body;
    insertOneFromTable({
        model:comment_model,
        data:body,
        res, 
    })
})

router.all("/getcomment",(req,res)=>{
    var body = req.body;
    FindAllFromTable({
        model:comment_model,
        query:{},
        res, 
    })
})

router.all("/delcomment",(req,res)=>{
    var body = req.body;
    removeOneFromTable({
        model:comment_model,
        query:body,
        res, 
    })
})

router.all("/setcomment",(req,res)=>{
    var body = req.body;
    updateOneFromTable({
        model:comment_model,
        query:{_id:body._id},
        data:body, 
        res, 
    })
})


// 商品列表 
router.all("/getgoodlist",(req,res)=>{
    var body = req.body;
    FindAllFromTable({
        model:good_model,
        query:body,
        res, 
    })
})

// 分页 （限制条数）
router.all("/getgoodlistlimit",(req,res)=>{
    var body = req.body;
    var {page=1,pageSize=10}=body
    // 先查所有
    FindAllFromTable({
        model:good_model,
        query:{},
        res, 
        // 回调
        callback:result=>{
            // 查出总得条数
            FindAllFromTable({
                model:good_model,
                query:{},  //条件为空
                res,
                skip:10,  //跳过多少跳
                limit:10,  //限制条数
            })
        }
    })
})

// 商品类型
router.all("/getgoodtype",(req,res)=>{
    var body = req.body;
    good_model.distinct('type')
    .then(result=>{
        res.json({
            code:200,
            result,
            msg:"获取分类成功"
        })
    })
})
// 商品列表 
router.all("/getgoodlist",(req,res)=>{
    var body = req.body;
    FindAllFromTable({
        model:good_model,
        query:body,
        res, 
    })
})

router.all("/getgoodone",(req,res)=>{
    var body = req.body;
    findOneFromTable({
        model:good_model,
        query:body,
        res, 
    })
})

// 查询点赞接口
router.all("/getlikes",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        FindAllFromTable({
            model:like_model,
            query:body,
            res,
            msg:"查询成功"
        })
    })
})

// 点赞
router.all("/addlikes",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        insertOneFromTable({
            model:like_model,
            data:body,
            res,
        })
    })
})
// 取消点赞
router.all("/dellikes",(req,res)=>{
    var body = req.body
    checkToken(req,res,({username})=>{
        removeOneFromTable({
            model:like_model,
            query:body,
            res,
        })
    })
})


// 查询收藏接口 

router.post("/getcollect",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        FindAllFromTable({
            model:shou_model,
            query:body,
            res,
            msg:"查询成功"
        })
    })
})

// 收藏
router.post("/addcollect",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        insertOneFromTable({
            model:shou_model,
            data:body,
            res,
        })
    })
})

// 取消收藏
router.post("/delcollect",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        removeOneFromTable({
            model:shou_model,
            query:body,
            res,
        })
    })
})

// // 购物车
// // 加入购物车
// router.all("/addCart", (req, res) => {
//     var body = req.body;
//     // 先判断是否存在
//     // 有 累加
//     // 没有 插入
//     console.log(body);
//     findOneTableData({
//       // 判断有没有
//       model:cart_Model,
//       res,
//       query: {
//         $or: [
//           {
//             goodId: body.goodId,
//             phone:body.phone
  
//           }
//         ]
//       },
//       callback: result => {
//         if (result) {
//           updateTableData({
//             model:cart_Model,
//             data: {
//               $set: {
//                 count: body.count + result.count  //数量累加
//               }
//             },
//             res,
//             msg: "添加成功1"
//           })
//         } else {
//           insertTableData({
//             // 没有插入
//             model:cart_Model,
//             res,
//             data: body,
//             msg: "添加成功",
//           })
//         }
//       }
//     })
//   })

// 查询购物车接口 
router.post("/getcart",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        FindAllFromTable({
            model:cart_model,
            query:body,
            res,
            msg:"查询成功"
        })
    })
})

// 添加购物车
router.post("/addcart",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        insertOneFromTable({
            model:cart_model,
            data:body,
            res,
        })
    })
})

// 删除购物车数据
router.post("/delcart",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        removeOneFromTable({
            model:cart_model,
            query:body,
            res,
        })
    })
})


// 修改 购物车数据
router.post("/setcart",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        updateOneFromTable({
            model:cart_model,
            query:{
                _id:body._id
            },
            data:body,
            res,
        })
    })
})

// 查询订单接口 
router.post("/payorder",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        FindAllFromTable({
            model:payorder_model,
            query:body,
            res,
            msg:"查询成功"
        })
    })
})


// 添加订单
router.all("/addpayorder",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        insertOneFromTable({
            model:payorder_model,
            data:body,
            res,
        })
    })
})


// 删除订单
router.all("/delpayorder",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        removeOneFromTable({
            model:payorder_model,
            query:body,
            res,
        })
    })
})

// 修改订单
router.all("/setpayorder",(req,res)=>{
    var body = req.body;
    checkToken(req,res,({username})=>{
        updateOneFromTable({
            model:payorder_model,
            query:{
                _id:body._id
            },
            data:body,
            res,
        })
    })
})



module.exports = router;

